<template>
  <slot
    name="before"
    v-bind="{ listValue, pull, add, swap }" />
  <slot
    v-for="(key, index) in listValue"
    :key="key"
    v-bind="{
      key,
      index,
      listValue,
      pull,
      add,
      swap,
      addBefore(value) {
        add(value, index);
      },
      addAfter(value) {
        add(value, index + 1);
      },
      first: index === 0,
      last: index === listValue.length - 1,
    }" />
  <slot
    name="after"
    v-bind="{ listValue, pull, add, swap }" />
</template>

<script>
export default {
  name: 'ListSlot',
  props: {
    modelValue: String,
    separator: {
      type: String,
      default: ',',
    },
  },
  emits: ['update:modelValue'],
  computed: {
    listValue: {
      get() {
        return (this.modelValue || '').split(this.separator).filter(Boolean);
      },
      set(value) {
        this.$emit('update:modelValue', value.join(this.separator));
      },
    },
  },
  methods: {
    pull(value) {
      this.listValue = this.listValue.filter(n => n !== value);
    },
    add(newValue, index = this.listValue.length) {
      let list = this.listValue.slice();
      list.splice(index, 0, newValue);
      this.listValue = list;
    },
    set(index, value) {
      let list = this.listValue.slice();
      list[index] = value;
      this.list = list;
    },
    swap(indexFrom, to) {
      let list = this.listValue.slice();
      list.splice(to, 0, list.splice(indexFrom, 1)[0]);
      this.listValue = list;
    },
  },
};
</script>

<style scoped></style>
